from ProjectTool.WebTool.base_func.base_func import BaseFunc
from utils.base_response import BaseResponse
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import re


# 工具列表
class ToolList(BaseFunc):
    def __init__(self,http_status,host,port,domain,local_storage,session_storage, driver=None,driver_status=None):
        super().__init__(http_status,host,port,domain,local_storage,session_storage,driver=driver,driver_status=driver_status)
        self.res = BaseResponse()
        self.page_url = 'OftenMyTool'  # url
        # self.run()
        self.table_fields = self._get_table_fields()  # 表格字段
        self._get_page_elements()  # 标签地址存放区
        self.page_data = {}  # 页面中需要验证的数据

    # 表格字段 及数据类型
    def _get_table_fields(self):
        return [('id', int), ('title', str), ('url', str), ('remark', str)]

    # 标签地址存放区
    def _get_page_elements(self):
        self.add_button = (By.XPATH, '//*[@id="app"]/div/section/section/main/div/div/div[1]/a/button')  # 添加按钮
        self.delete_button = (By.XPATH, '//*[@id="app"]/div/section/section/main/div/div/div[1]/button')  # 批量删除
        self.operation_table_edit = (
            By.XPATH,
            '//div[@class="el-table__fixed-body-wrapper"]/table/tbody/tr[{tr}]/td[6]//span[contains(text(),"编辑")]')  # 编辑 {tr}
        self.operation_table_delete = (
            By.XPATH,
            '//div[@class="el-table__fixed-body-wrapper"]/table/tbody/tr[{tr}]/td[6]//span[contains(text(),"删除")]')  # 删除 {tr}
        self.search_box = (By.XPATH, '//*[@id="app"]/div/section/section/main/div/div/div[2]/div/input')  # 搜索框
        self.search_box_button = (
            By.XPATH, '//*[@id="app"]/div/section/section/main/div/div/div[2]/div/div/button')  # 搜索按钮
        self.table_thead_data = (By.XPATH, '//table/thead/tr/th[*]/div'),  # 表头数据
        self.table_tbody_data = (
            By.XPATH, '//div[@class="el-table__body-wrapper is-scrolling-left"]/table/tbody')  # 表体数据
        # 分页组件
        self.data_article_number = (
            By.XPATH, '//div[@class="el-pagination"]//span[@class="el-pagination__total"]')  # 数据条数
        self.table_row_input = (By.XPATH, '//span[@class="el-pagination__sizes"]')  # 表格条数输入框
        self.table_row_numbers = (By.XPATH, '//div[@class="el-scrollbar"]//ul/li[*]')  # 页面条数列表
        self.table_page_elements = (By.XPATH, '//ul[@class="el-pager"]/li')  # 表格页数标签
        self.table_page_next = (By.XPATH, '//button/span[contains(text(),"下一页")]')  # 下一页按钮
        self.table_page_previous = (By.XPATH, '//button/span[contains(text(),"下一页")]')  # 上一页按钮
        self.select_page = (By.XPATH, '//ul[@class="el-pager"]/li[@class="number active"]')  # 被选中页
        self.table_page_input = (By.XPATH, '//span[@class="el-pagination__jump"]//input')  # 前往页数

    # 页面中需要验证的数据
    def _get_page_data(self):
        return self.page_data

    # 获取表格标签及对应数据（当前页）
    def _get_table_data(self, *args, **kwargs):
        elements = self.find_element(self.table_tbody_data).find_elements(By.TAG_NAME, 'tr')
        td_elements = []  # 符合条件的标签
        tb_text_data = []  # 符合条件的数据
        rows = []  # 符合条件的行数
        for index, element in enumerate(elements, 1):
            status = True
            ele = element.find_elements(By.TAG_NAME, 'td')
            ele_texts = self.get_elements_text(ele)
            ele_dict = {field_tup[0]: field_tup[1](ele_texts[index]) for index, field_tup in
                        enumerate(self.table_fields, 1)}
            for kwa in kwargs:
                if ele_dict.get(kwa) != kwargs.get(kwa):
                    status = False
            if status:
                td_elements.append(ele)
                tb_text_data.append(ele_dict)
                rows.append(index)
        return {
            'td_elements': td_elements,  # 对应元素对象
            'tb_text_data': tb_text_data,  # 的对应文本数据
            'rows': rows  # 行数
        }

    # 输入内容
    def send_search(self,*args, **kwargs):
        send_field = 'title'
        title = kwargs.get(send_field)
        element_input = self.find_element(self.search_box)
        self.send_keys(element_input, title)
        self.page_data[send_field] = title
        return self._get_page_data()

    # 点击搜索
    def click_search(self,*args, **kwargs):
        element_search = self.find_element(self.search_box_button)
        self.click(element_search)
        data = self._get_table_data()
        data_count = self.get_table_row_number()
        self.page_data['page_data'] = data.get('tb_text_data')
        self.page_data['data_count'] = data_count
        return self._get_page_data()

    # 点击添加按钮
    def add_row_element(self,*args, **kwargs):
        add_element = self.find_element(self.add_button)
        self.click(add_element)

    # 点击编辑按钮
    def edit_row_element(self, *args, **kwargs):
        table_dict = self._get_table_data(*args, **kwargs)
        rows = table_dict['rows']
        if len(rows) > 1:
            print('匹配数量大于1，无法编辑！')
        elif len(rows) == 0:
            print('未匹配到对应数据')
        else:
            path = self.operation_table_edit[1].format(tr=rows[0])
            elements = self.find_elements((self.operation_table_edit[0], path))
            self.click(elements[0])

    # 点击删除按钮
    def delete_row_element(self, *args, **kwargs):
        table_dict = self._get_table_data(*args, **kwargs)
        rows = table_dict['rows']
        if len(rows):
            for row in rows[::-1]:
                path = self.operation_table_delete[1].format(tr=row)
                element = self.find_element((self.operation_table_delete[0], path))
                self.click(element)

    # 选中数据
    def select_row_elements(self, *args, **kwargs):
        table_dict = self._get_table_data(*args, **kwargs)
        td_elements = table_dict['td_elements']
        for elements in td_elements:
            elements[0].click()

    # 删除选中的数据
    def delete_row_elements(self,*args, **kwargs):
        elements = self.find_element(self.delete_button[0])
        self.click(elements)

    # 获取表格数据
    def get_table_data(self, *args, **kwargs):
        table_dict = self._get_table_data(*args, **kwargs)
        return table_dict['tb_text_data']

    # 选择表格某行或某几行
    def select_table_tr(self, *args, **kwargs):
        table_dict = self._get_table_data(*args, **kwargs)
        td_elements = table_dict['td_elements']
        for ele in td_elements:
            self.click(ele[0])

    # 获取数据总条数
    def get_table_row_number(self,*args, **kwargs):
        element = self.find_element(self.data_article_number)
        text = self.get_element_text(element)
        row_number = re.findall('\d+', text)
        row_number = int(row_number[0]) if row_number else 0
        return row_number

    # 修改每页的条数
    def edit_table_rows(self,*args, **kwargs):
        row_number = kwargs.get('row_number')
        self.click(self.find_element(self.table_row_input))
        page_numbers = self.find_elements(self.table_row_numbers)
        page_numbers_text = self.get_elements_text(page_numbers)
        print('page_numbers_text:', page_numbers_text)
        if isinstance(row_number, int) and row_number >= 0 and row_number < len(page_numbers):
            self.click(page_numbers[row_number])

    # 选则页数
    def select_page_number(self,*args, **kwargs):
        page_number = kwargs.get('page_number')
        pages = self.find_elements(self.table_page_elements)
        if isinstance(page_number, int) and page_number >= 0 and page_number < len(pages):
            self.click(pages[page_number])
        time.sleep(2)

    # 进入对应页数
    def to_page_number(self,*args, **kwargs):
        page_number = kwargs.get('page_number')
        element = self.find_element(self.select_page)
        text = self.get_element_text(element)
        element = self.driver.find_element(*self.table_page_input)
        for i in range(len(text)):
            element.send_keys(Keys.BACK_SPACE)
        element.send_keys(page_number)
        self.click(self.find_element(self.search_box))
        time.sleep(3)


if __name__ == '__main__':
    tool_obj = ToolList()
    # now_url = tool_obj.driver.current_url
    # print(now_url)
    tool_obj.to_page_number(3)  # 输入页数
    tool_obj.drag_down()  # 往下拉动一屏
    # [('id', int), ('title', str), ('URL', str), ('remark', str)]
    tool_obj.delete_row_element(remark='备注哈哈哈哈哈啊沙发沙发沙发沙发沙发的111')  # 删除

    data = tool_obj._get_table_data()
    print('data:', data)
    tool_obj.select_row_elements()
    # data = tool_obj.get_table_data(id=4)  # 获取数据
    # print('td_elements_text:', data)
    # tool_obj.select_table_tr(id=3)  # 选中符合条件的数据
    # tool_obj.send_search('json数据查看工具')  # 搜索
    # tool_obj.click_search()  # 点击搜索
    # tool_obj.send_search(' ')  # 搜索
    # tool_obj.click_search()  # 点击搜索
    # tool_obj.edit_row_element(id=4)  # 编辑
    # tool_obj.back()  # 后退
    # tool_obj.add_row_element()  # 添加
    # tool_obj.back()  # 后退
    # tool_obj.get_table_row_number()  # 数据总条数
    # tool_obj.edit_table_rows(2)  # 修改每页的条数
    # tool_obj.edit_table_rows(0)  # 修改每页的条数
    # tool_obj.select_page_number(1)  # 选择页数
    # tool_obj.to_page_number(1)  # 输入页数
    # tool_obj.drag_down()  # 往下拉动一屏
    # tool_obj.forward()  # 前进

    time.sleep(5)
    tool_obj.quit()
